<template>
  <wd-drop-menu>
    <wd-drop-menu-item
      v-model="cityValue"
      :options="cityOptions"
      value-key="adcode"
      label-key="name"
    />
    <wd-drop-menu-item
      v-model="countryValue"
      :options="countryOptions"
      value-key="adcode"
      label-key="name"
      @change="changeCountry"
    />
  </wd-drop-menu>
</template>

<script setup>
import { DEFAULT_CITY_CODE, DEFAULT_COUNTRY_CENTER, DEFAULT_COUNTRY_CODE } from '@/configs/constant'
import allAreas from '@/static/zjGeo.json'

const cityValue = ref(DEFAULT_CITY_CODE)
const countryValue = ref(DEFAULT_COUNTRY_CODE)
const currentCountryCenter = ref(DEFAULT_COUNTRY_CENTER)

const areaData = ref(allAreas)
const cityOptions = ref(allAreas)
// const countryOptions = ref([])

const countryOptions = computed(() => {
  const countryOpts = cityOptions.value.find((item) => item.adcode === cityValue.value)?.districts
  return countryOpts || []
})

const emits = defineEmits(['change'])

watch(
  () => cityValue.value,
  (val) => {
    const { adcode, center } = countryOptions.value[0]
    countryValue.value = adcode
    currentCountryCenter.value = center
    emits('change', { city: val, country: adcode, center })
  },
)

const changeCountry = ({ selectedItem }) => {
  const { adcode, center } = selectedItem
  emits('change', { city: cityValue.value, country: adcode, center })
}
</script>
